import { apiDomain } from '../constant/api';

/**
 * 获取url中的参数值
 * @param key
 */
export const $getQueryString = (key) => {
    const href = window.location.href;
    const index = href.lastIndexOf('?');
    if(index>0){
        const search = href.substring(index,href.length);
        return $getQueryByString(search, key);
    }
    return '';
};

/**
 * 获取指定字符串中的value值
 * @param searchStr
 * @param key
 */
export const $getQueryByString = (searchStr, key) => {
    let reg = new RegExp('(^|&)' + key + '=([^&]*)(&|$)', 'i');
    let r = searchStr.substr(1).match(reg);
    if (r != null) {
        return decodeURIComponent(r[2]);
    }
    return '';
};

/**
 * 统一接口，获取用户状态信息
 */
export const $getAccessInfo = () => {
    let result = {
        token: ''
    };

    result.token = localStorage.getItem(accessInfoKey.token) || '';

    return result;
};

(window as any).$getAccessInfo = $getAccessInfo;

/**
 * 格式化json对象为a=1&b=2的格式
 * @param urlParams json对象
 * @returns {string}
 */
export const parseUrlParmas = (urlParams) => {
    if (!urlParams || (typeof urlParams !== 'object')) {
        return '';
    }
    const keys = Object.keys(urlParams);
    if (keys.length === 0) {
        return '';
    }

    let result = '';
    keys.forEach(key => {
        result += `&${key}=${encodeURIComponent(urlParams[key])}`;
    });
    result = result.replace('&', '');
    return result;
};

/**
 * 统一处理response方法
 * @param response
 * @param callback
 */
export const handleResponse = (response, callback) => {
    const body = response.body || {};
    if (response.success && (body.code === '200' || body.code === 200 || body.code === '0')) {
        callback.success(body);
    }
    else if (response.success && body.code !== '200') {
        callback.fail && callback.fail(body.msg || '', body.code);
    }
    else {
        if (callback.error) {
            callback.error(response.error);
        } else {
            callback.fail && callback.fail(body.msg || '', body.code);
        }
    }
};

/**
 * 获取头信息
 * @param headers
 */
export const getHeaders = (headers = {}) => {
    const accessInfo = $getAccessInfo();
    let more = {
        token: accessInfo.token,
    };
    if(apiDomain.env === project_ENV.uat){
        more["SERVICE-AUTHENTICATION"] = 'eyJhbGciOiJIUzI1NiJ9.eyJzZXJ2aWNlTmFtZSI6IjM5MiIsInNlcnZpY2VLZXkiOiIxMGEyZDdkZTcyOGM0NjMyYmEzNDEwODFiOTk4MWMxZiIsInNlcnZpY2VUeXBlIjoiMSIsInNlcnZpY2VBcHAiOiIxODMiLCJzZXJ2aWNlQ2x1c3RlciI6IjMiLCJqdGkiOiI0MWI3Mzc4ZmRlYTU0NzA4OGMxMjk4MjE3OWUxYTVjYSIsImlhdCI6MTU1NTY0ODI0N30.Z_4q5UHYM6jUQsbkfAmNa_4jM8wPSmcRiQyawYq8tIY';
    }
    else if(apiDomain.env === project_ENV.production){
        more["SERVICE-AUTHENTICATION"] = 'eyJhbGciOiJIUzI1NiJ9.eyJzZXJ2aWNlTmFtZSI6IjM5MiIsInNlcnZpY2VLZXkiOiIxMzQ1MTEyZGI4YmE0MjBhYjI1MzNjOTc1NjgzNjBjNCIsInNlcnZpY2VUeXBlIjoiMSIsInNlcnZpY2VBcHAiOiIxODMiLCJzZXJ2aWNlQ2x1c3RlciI6IjEwIiwianRpIjoiOWU2ODQ0M2E2ZDFiNDllNzk1YTNlZGFmODJhZmQxNjEiLCJpYXQiOjE1NTU5MDU5NDl9.rYH1XF9xjUgW9w-4XD6OxVzal_iK3qLvPxzkPBfo0fI';
    }
    if (headers) {
        return Object.assign({}, more, headers);
    } else {
        return more;
    }
};

export const getWindowHeight = ()=>{
    return document.body.clientHeight;
};


const filterTree = (dataSource, filter) => {
    let result = [];
    loopTree(dataSource, filter, result);
    return result;
};

const loopTree = (dataSource, filter, result) => {
    for (let i = 0; i < dataSource.length; i++) {
        const item = dataSource[i];
        if (filter(item)) {
            result.push(item);
            break;
        } else if (item.child && item.child.length > 0) {
            loopTree(item.child, filter, result);
        }
    }
};

export const getMenuById = (id, dataSource) => {
    return filterTree(
        dataSource,
        o => o.id === id
    )
};
export const loopDataTree = (dataSource, filter, result, childKey = 'children') => {
    for (let i = 0; i < dataSource.length; i++) {
        const item = dataSource[i];
        const _children = item[childKey] || [];
        if (filter(item)) {
            result.push(item);
            break;
        } else if (_children.length > 0) {
            loopDataTree(_children, filter, result);
        }
    }
};
